﻿#include "commonhelper.h"
#include <QApplication>
#include <QClipboard>
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QQuickWindow>

CommonHelper::CommonHelper()
{
    m_try=new QTimer(this);
    m_try->setInterval(3 * 60 * 60 * 1000);
    connect(m_try,&QTimer::timeout,this,[this]()
            {
                m_try->stop();
                QMessageBox::information(nullptr,u8"提示",u8"试用结束");
                qApp->exit();
            });
    //m_try->start();
}

CommonHelper *CommonHelper::instance()
{
    static CommonHelper global;
    return &global;
}

void CommonHelper::setValue(const QString &key, const QVariant &value)
{
    m_settings.setValue(key,value);
}

QVariant CommonHelper::getValue(const QString &key)
{
    return m_settings.value(key);
}

void CommonHelper::clipboardText(const QString &str)
{
    QApplication::clipboard()->setText(str);
}

QVariant CommonHelper::openImageDialog()
{
    QString filePath = QFileDialog::getOpenFileName(      nullptr,
                                 u8"选择图片文件",
                                 "",
                                                    "Images (*.png *.jpg);;All Files (*)");
    if(filePath.isEmpty())
    {
        return QVariant();
    }


    QVariantMap res;
    QFileInfo finfo(filePath);
    qDebug()<<"=======openImageDialog======"<<filePath<<finfo.size();
    if(finfo.size() >= 5 * 1024 * 1024)
    {
        res["code"]=1;
        res["message"]=u8"头像不得超过5M";
        return res;
    }
    res["code"]=0;
    res["file"]=filePath;
    return res;
}

bool CommonHelper::question(QObject* obj,const QString &str)
{
    QWindow* win=qobject_cast<QWindow*>(obj);
    QRect rc=  win->geometry();
    QMessageBox mess(QMessageBox::Question, tr(u8"提示"), str, QMessageBox::NoButton, nullptr,Qt::Dialog | Qt::Tool);
    mess.addButton(tr(u8"确定"), QMessageBox::AcceptRole);
    mess.addButton(tr(u8"取消"),QMessageBox::RejectRole);
    mess.show();
    mess.move(rc.left() + rc.width() / 2 - mess.width()  / 2,rc.top() + rc.height() / 2 - mess.height() / 2);
    return  mess.exec()== 0;
}
